<?php


function includeDirectory($path, $array)
{
    foreach ($array as $item) {
        if (strpos($path, $item) !== false) {
            return true;
        }
    }
    return false;
}

function replaceInFiles($directory, $search, $replace) {
    $dir = new RecursiveDirectoryIterator($directory);
    $ite = new RecursiveIteratorIterator($dir);

    foreach ($ite as $file) {
        if ($file->isFile()) {
            $filePath = $file->getRealPath();
            $content = file_get_contents($filePath);
            $newContent = str_replace($search, $replace, $content);
            if ($content !== $newContent) {
                file_put_contents($filePath, $newContent);
            }
        }
    }
}

function deleteDirectory($dir)
{
    echo "deleteDirectory {$dir}\r\n";
    if (!file_exists($dir)) {
        return false;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        $path = $dir . DIRECTORY_SEPARATOR . $item;

        if (is_dir($path)) {
            deleteDirectory($path);
        } else {
            unlink($path);
        }
    }

    return rmdir($dir);
}

function createDirectory($dir)
{
    echo "createDirectory {$dir}\r\n";
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
}

/**
 * exceptfilenames 不包含的文件名，比如 ["*.php"]
 */
function xcopy($source, $destination,$exceptfilenames=[], $isEcho=true)
{
    if($isEcho===true){
        echo "xcopy {$source} , {$destination}\r\n";
        echo "  excpetion paths:".join(',',$exceptfilenames);
    }
    createDirectory($destination);
    if (is_dir($source)) {
        $dir = opendir($source);
        while (false !== ($file = readdir($dir))) {
            if ($file != '.' && $file != '..') {
                if(includeDirectory("{$source}/{$file}",$exceptfilenames)===false){
                    if (is_dir("{$source}/{$file}")) {
                        createDirectory("{$destination}/{$file}");
                        xcopy("{$source}/{$file}", "{$destination}/{$file}",$exceptfilenames,false);
                    } else {
                       copy("{$source}/{$file}", "{$destination}/{$file}");
                    }
                }else{
                    echo "   =======>xcopy ignore path:{$source}/{$file}\r\n";
                }
            }
        }
        closedir($dir);
    }
}


function deleteFile($dir, $filenamepattern)
{
    if ($handle = @opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            if (($file == '.') || ($file == '..')) {
                continue;
            }
            $fullpath = $dir . '/' . $file;
            if (is_dir($fullpath)) {
                if (_isMatch($filenamepattern, $file) === true) {
                    echo 'Delete Path:' . $fullpath . "\r\n";
                    deleteFile($fullpath, '/.*/');
                    rmdir($fullpath);
                }
                deleteFile($fullpath, $filenamepattern);
            } else {
                if (_isMatch($filenamepattern, $file) === true) {
                    echo 'Delete File:' . $fullpath . "\r\n";
                    unlink($fullpath);
                }
            }
            preg_match($filenamepattern, $file, $match);
        }
        @closedir($handle);
    }
}

function _isMatch($pattern, $string)
{
    preg_match($pattern, $string, $match);
    if ($match != null) {
        return true;
    } else {
        return false;
    }
}



function zipDirectory($sourcePath, $zipname)
{
    $zip = new ZipArchive();
    if ($zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        addFileToZip($sourcePath, $zip, $sourcePath); //调⽤⽅法，对要打包的根⽬录进⾏操作，并将ZipArchive的对象传递给⽅法
        $zip->close(); //关闭处理的zip⽂件
    }
}


function addFileToZip($path, $zip, $relativePath)
{

    echo " addFileToZip-path:{$path}\r\n";
    // echo " addFileToZip-zip:{$zip}\r\n";
    $handler = opendir($path); //打开当前⽂件夹由$path指定。
    while (($filename = readdir($handler)) !== false) {
        //echo "  ADD ZIP:{$filename}\r\n";
        if ($filename != "." && $filename != "..") { //⽂件夹⽂件名字为'.'和‘..'，不要对他们进⾏操作
            //echo $path.DIRECTORY_SEPARATOR.$filename."===============\r\n";
            //echo substr($path,strlen($relativePath)+1).DIRECTORY_SEPARATOR.$filename."\r\n";
            if (is_dir($path . DIRECTORY_SEPARATOR . $filename)) { // 如果读取的某个对象是⽂件夹，则递归
                addFileToZip($path . DIRECTORY_SEPARATOR . $filename, $zip, $relativePath);
            } else { //将⽂件加⼊zip对象
                $rpath = substr($path, strlen($relativePath) + 1) . DIRECTORY_SEPARATOR . $filename;
                if (strpos($rpath, DIRECTORY_SEPARATOR) == 0) {
                    $rpath = substr($rpath, 1);
                }
                $rpath = str_replace("\\\\", DIRECTORY_SEPARATOR, $rpath);
                $rpath = str_replace("\\", DIRECTORY_SEPARATOR, $rpath);
                $rpath = str_replace(DIRECTORY_SEPARATOR, '/', $rpath);
                //$rpath = str_replace("\\",DIRECTORY_SEPARATOR,$rpath);
                $zip->addFile($path . DIRECTORY_SEPARATOR . $filename, $rpath);
            }
        }
    }
    //die();	
    if (is_resource($path)) {
        @closedir($path);
    }
}
